package cc.javaee.bbs.controller.api;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import cc.javaee.bbs.model.activity.KbrActivityPrize;
import cc.javaee.bbs.vo.RankingVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cc.javaee.bbs.constants.Constants;
import cc.javaee.bbs.exception.ResultException;
import cc.javaee.bbs.model.Huifu;
import cc.javaee.bbs.model.KbrPrizeCustomer;
import cc.javaee.bbs.model.activity.KbrActivity;
import cc.javaee.bbs.model.activity.KbrActivityCustomer;
import cc.javaee.bbs.model.activity.KbrActivityFile;
import cc.javaee.bbs.params.WebParams;
import cc.javaee.bbs.request.KoboroRequest;
import cc.javaee.bbs.service.HuifuService;
import cc.javaee.bbs.service.activity.ActivityDynamicService;
import cc.javaee.bbs.service.activity.ActivityService;
import cc.javaee.bbs.tool.PublicStatic;
import cc.javaee.bbs.tool.Tool;
import cc.javaee.bbs.vo.ActivityDetailsVo;
import cc.javaee.bbs.vo.ActivityVO;
import cc.javaee.bbs.vo.ResultVO;

/*
 * 活动接口
 * 
 */
@Controller
@RequestMapping("/appInteface/activity")
public class ActivityController {

    @Autowired
    ActivityService activityService;
    @Autowired
    ActivityDynamicService activityDynamicService;
    @Autowired
    HuifuService huifuService;

    /**
     * 活动报名接口
     *
     * @param request http://localhost:8010/bbs/appInteface/activity/signUp.do?custId=1&&actId=1&&archivalNumber=987987
     */
    @ResponseBody
    @RequestMapping("signUp")
    public ResultVO signUp(HttpServletRequest request) throws ParseException {
        String actId = request.getParameter("actId");
        String archivalNumber = request.getParameter("archivalNumber");
        try {
            activityService.signUp(Integer.parseInt(actId), archivalNumber);
        } catch (ResultException e) {
            e.printStackTrace();
            return ResultVO.error(e.getCode(), e.getMsg());
        }
        return ResultVO.success();
    }

    /**
     * 活动列表接口
     *
     * @param request http://localhost:8080/bbs/appInteface/activity/actList.do?status=已结束
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping(value = "actList", produces = {"application/json"})
    public ResultVO actList(HttpServletRequest request, KbrActivity activity, @RequestParam("archivalNumber") String archivalNumber) throws ParseException {
//        String status = request.getParameter("status");
//        WebParams param = new WebParams();
//        param.put("status", activity.getStatus());
//        BizOutMap out = new BizOutMap();
//        out = activityService.findDbList(param);
//        out.put("actList", activityService.grouping((List<DbResultMap>) out.get("actList")));
//        return out;
        List<KbrActivity> kbrActivities = activityService.find(activity);

        Map<Integer, List<ActivityVO>> collect = kbrActivities.stream()
                .map(ActivityVO::convertKbrActivity)
                .collect(Collectors.groupingBy(ActivityVO::getStatus));

        collect.forEach((k, v) -> v.forEach(e -> {
            // 查询是否参加活动
            List<KbrActivityCustomer> customer = activityService.findCustomer(e.getId(), archivalNumber);
            if (CollectionUtils.isNotEmpty(customer)) {
                e.setMyStatus(1);
            } else {
                e.setMyStatus(0);
            }
        }));

        return ResultVO.success(collect);
    }

    /**
     * 活动详情接口  http://localhost:8080/bbs/appInteface/activity/actInfo/35.do?archivalNumber=20171011000002
     *
     * @param id
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping("actInfo/{id}")
    public ResultVO actInfo(@PathVariable Integer id,
                            @RequestParam("archivalNumber") String archivalNumber,
                            @RequestParam(value = "showCount", required = false) Integer showCount) throws ParseException {
        ActivityDetailsVo activityEnd = new ActivityDetailsVo();
        // 获取活动
        KbrActivity activity = activityService.findById(id);
        if (activity == null) {
            ResultVO.error(-1, "活动不存在");
        }
        activityEnd.process(activity.getArrangeList());
        activityEnd.setDescribe(activity.getDescriber());

        //设置活动状态
        //活动尚未开始
        if (Constants.ActivityStatus.NOT_STARTED == activity.getStatus()) {
            //报名尚未开始
            if (Constants.SignStatus.NOT_STARTED == activity.getSignStatus()) {
                activityEnd.setStatus(0);
            } else {
                activityEnd.setStatus(1);
            }
        } else if (Constants.ActivityStatus.STARTING == activity.getStatus()) {
            // 活动
            activityEnd.setStatus(2);
        } else {
            activityEnd.setStatus(3);
        }

//        if (Constants.ActivityStatus.NOT_STARTED == activity.getStatus()) {
        Date enStartTime = activity.getEnStartTime();
        activityEnd.setTimeLeftSignUp(enStartTime);
//        }

        // 报名人员
        List<KbrActivityCustomer> customers = activityService.findCustomer(id, null);
        Map<Integer, KbrActivityCustomer> applyMembers = customers.stream().collect(Collectors.toMap(KbrActivityCustomer::getCustId, e -> e));
        activityEnd.setApplyMembers(applyMembers);

        long count = customers.stream().filter(e -> archivalNumber.equals(e.getArchivalNumber())).count();
        if (count > 0) {
            activityEnd.setMySignUpStatus(1);
        } else {
            activityEnd.setMySignUpStatus(0);
        }

        // 获取参与人员
        String triggerType = activity.getTriggerType();
        activityEnd.setType(triggerType);
        if (Constants.TriggerType.UPLOAD_FILES.equals(triggerType)) {

            //获取热门参与 participation
            List<Huifu> ranking = activityService.huifuRanking(activity, customers);
            activityEnd.participation(ranking);

            //获取点赞数
            List<Huifu> likes = activityService.huifuList(id, 4, customers);
            if (CollectionUtils.isNotEmpty(likes)) {
                activityEnd.setLikeCount(likes.size());
            }
            activityEnd.setParticipationCount(customers.size());
        } else {
            activityEnd.setWalkCount(activity.getWalkCount());
            // 接口获取
            if (CollectionUtils.isNotEmpty(customers)) {
                List<String> archivalNumberlist = customers.stream().map(KbrActivityCustomer::getArchivalNumber).collect(Collectors.toList());
                Map ranking = KoboroRequest.getRanking(archivalNumberlist, activity.getStartTime(), activity.getEndTime());
                activityEnd.participationSYS(ranking);
            }
            Date date = new Date();
            Map allWalk = KoboroRequest.getAllWalk(archivalNumber, date, date);
//            activityEnd.setCurrentWalkCount(allWalk.get("data") != null ? (int) allWalk.get("data") : 0);
            activityEnd.setCurrentWalkCount(111);
        }

        activityEnd.setActId(id);
        activityEnd.setName(activity.getName());
        // 活动图片
        List<KbrActivityFile> actFileList = activity.getActFileList();
        if (CollectionUtils.isNotEmpty(actFileList)) {
            activityEnd.setImgPath(actFileList.get(0).getFilePath());
        }
        //广告图片
        List<KbrActivityFile> adFileList = activity.getAdFileList();
        if (CollectionUtils.isNotEmpty(adFileList)) {
            activityEnd.setAdvImgPath(adFileList.get(0).getFilePath());
        }

        // 获取排名
        List<KbrPrizeCustomer> prizeCustomer = activityService.getPrizeCustomer(id);
        activityEnd.ranking(prizeCustomer);

        // 获取奖品
        List<KbrActivityPrize> prizes = activityService.getPrizesBreakp(id);
        activityEnd.setPrizes(prizes);

        // 获取评论
        List<Huifu> huifus = activityService.huifuList(id, Constants.HuifuType.HUIFU, customers);
        activityEnd.discuss(huifus);

        if (showCount != null && showCount > 0) {
            List reply = activityEnd.getReply();
            if (CollectionUtils.isNotEmpty(reply) && reply.size() > showCount) {
                List list = reply.subList(0, showCount);
                activityEnd.setReply(list);
            }
        }

        return ResultVO.success(activityEnd);
    }

    /**
     * 回复
     */
    @ResponseBody
    @RequestMapping("huifu/{type}")
    public ResultVO actInfo() {

        return ResultVO.success();
    }

    /**
     * 上传文件
     * http://localhost:8010/bbs/appInteface/activity/uploadFile.do?actId=1&&file=
     *
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("uploadFile.do")
    public Map<String, String> findAllWhere(HttpServletRequest request) throws IOException {
        String actId = request.getParameter("actId");        //0代表失败，1代表成功，2格式错误
        Map<String, String> map = new HashMap<String, String>();
        // 转型为MultipartHttpRequest  
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> fileList = new ArrayList<MultipartFile>();
            fileList = multipartRequest.getFiles("file");
            if (fileList == null || fileList.size() == 0) {
                fileList = multipartRequest.getFiles("actFile");
            }
            if (fileList == null || fileList.size() == 0) {
                fileList = multipartRequest.getFiles("adFile");
            }

            for (MultipartFile mf : fileList) {
                if (!mf.isEmpty()) {
                    try {
                        // 文件保存路径  
                        String dirname = "image/" + Tool.getyyyyMMdd();
                        String filePath = PublicStatic.FILE_PATH + dirname + "/";

                        filePath = filePath.replace("bbs", "");
                        File file = new File(filePath);
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        String filenamelast = getfilenamelast(mf.getOriginalFilename()).toUpperCase();
                        if (!filenamelast.equals(".JPG") && !filenamelast.equals(".GIF") && !filenamelast.equals(".JPEG") && !filenamelast.equals(".PNG") && !filenamelast.equals(".SWF")) {
                            map.put("isok", "2");
                        } else {
                            filenamelast = Tool.getyyyyMMddHHmmssSSS() + Tool.getRandom() + filenamelast;
                            map.put("isok", "1");
                            map.put("path", dirname + "/" + filenamelast);
                            // 转存文件
                            mf.transferTo(new File(filePath + filenamelast));
                        }
                    } catch (Exception e) {
                        map.put("isok", "0");
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        if ((map.get("isok") + "").equals("1")) {
            String path = map.get("path") + "";
            WebParams param = new WebParams();
            param.put("actId", actId);
            param.put("path", path);
            activityDynamicService.saveDynamic(param);
        }
        return map;
    }

    //获取文件名
    private String getfilenamelast(String filename) {
        int start = filename.lastIndexOf(".");
        if (start != -1) {
            filename = filename.substring(start, filename.length());
        }
        return filename;
    }

    /**
     * 排行榜接口
     *
     * @param request http://localhost:8086/bbs/appInteface/activity/leaderboard.do?actId=1
     */
    @ResponseBody
    @RequestMapping("leaderboard")
    public ResultVO leaderboard(HttpServletRequest request) throws ParseException {
        String actId = request.getParameter("actId");//活动id
        String archivalNumber = request.getParameter("archivalNumber");//活动id
        try {
            RankingVO leaderboard = activityService.leaderboard(Integer.parseInt(actId), archivalNumber);
            return ResultVO.success(leaderboard);
        } catch (ResultException e) {
            e.printStackTrace();
            return ResultVO.error(e.getCode(), e.getMsg());
        }
    }

}
